<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

interface PointPackage {
  id: string
  name: string
  description?: string
  pointsAmount: string
  priceDecimal: string
  imageUrl?: string
  badge?: string
  sortOrder: number
  isActive: boolean
  isRecommended: boolean
  createdAt: string
  updatedAt: string
}

const packageList = ref<PointPackage[]>([])
const packageForm = reactive({
  name: '',
  description: '',
  pointsAmount: 0,
  priceDecimal: 0,
  imageUrl: '',
  badge: '',
  sortOrder: 0,
  isActive: true,
  isRecommended: false
})
const packageDialog = ref(false)
const editingId = ref<string | null>(null)

async function fetchPackages() {
  try {
    const { data } = await request.get('/api/admin/point-packages')
    packageList.value = data
  } catch (error) {
    ElMessage.error('포인트 상품 패키지 목록 가져오기 실패')
  }
}

function resetForm() {
  packageForm.name = ''
  packageForm.description = ''
  packageForm.pointsAmount = 0
  packageForm.priceDecimal = 0
  packageForm.imageUrl = ''
  packageForm.badge = ''
  packageForm.sortOrder = 0
  packageForm.isActive = true
  packageForm.isRecommended = false
  editingId.value = null
}

function openCreateDialog() {
  resetForm()
  packageDialog.value = true
}

function openEditDialog(row: PointPackage) {
  packageForm.name = row.name
  packageForm.description = row.description || ''
  packageForm.pointsAmount = Number(row.pointsAmount)
  packageForm.priceDecimal = Number(row.priceDecimal)
  packageForm.imageUrl = row.imageUrl || ''
  packageForm.badge = row.badge || ''
  packageForm.sortOrder = row.sortOrder
  packageForm.isActive = row.isActive
  packageForm.isRecommended = row.isRecommended
  editingId.value = row.id
  packageDialog.value = true
}

async function savePackage() {
  if (!packageForm.name || !packageForm.pointsAmount || !packageForm.priceDecimal) {
    ElMessage.error('이름, 포인트 수량, 가격을 입력하세요')
    return
  }

  try {
    if (editingId.value) {
      // 편집
      await request.put(`/api/admin/point-packages/${editingId.value}`, packageForm)
      ElMessage.success('업데이트 성공')
    } else {
      // 신규 추가
      await request.post('/api/admin/point-packages', packageForm)
      ElMessage.success('생성 성공')
    }
    packageDialog.value = false
    await fetchPackages()
  } catch (error) {
    ElMessage.error(editingId.value ? '업데이트 실패' : '생성 실패')
  }
}

async function togglePackage(row: PointPackage) {
  try {
    await request.put(`/api/admin/point-packages/${row.id}`, { isActive: !row.isActive })
    ElMessage.success('상태 업데이트 성공')
    await fetchPackages()
  } catch (error) {
    ElMessage.error('상태 업데이트 실패')
  }
}

async function toggleRecommended(row: PointPackage) {
  try {
    await request.put(`/api/admin/point-packages/${row.id}`, { isRecommended: !row.isRecommended })
    ElMessage.success('추천 상태 업데이트 성공')
    await fetchPackages()
  } catch (error) {
    ElMessage.error('추천 상태 업데이트 실패')
  }
}

async function deletePackage(row: PointPackage) {
  try {
    await ElMessageBox.confirm('이 포인트 상품 패키지를 삭제하시겠습니까?', '삭제 확인', {
      confirmButtonText: '확인',
      cancelButtonText: '취소',
      type: 'warning',
    })

    await request.delete(`/api/admin/point-packages/${row.id}`)
    ElMessage.success('삭제 성공')
    await fetchPackages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 실패')
    }
  }
}

function formatPoints(points: string) {
  return Number(points).toLocaleString()
}

function formatPrice(price: string) {
  return Number(price).toLocaleString('zh-CN', { minimumFractionDigits: 2 })
}

// 이미지 업로드 성공 처리
function handleImageSuccess(res: any) {
  if (res?.coverUrl) {
    packageForm.imageUrl = res.coverUrl
  }
}

// 이미지 URL 가져오기 (상대 경로와 절대 경로 처리)
function getImageUrl(url: string) {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `${API_BASE_URL}${url}`
}

onMounted(() => {
  fetchPackages()
})
</script>

<template>
  <div class="package-mgmt">
    <h2 class="title">포인트 상품 패키지 관리</h2>

    <div class="toolbar">
      <el-button type="primary" :icon="Plus" @click="openCreateDialog">상품 패키지 추가</el-button>
      <el-button :icon="Refresh" @click="fetchPackages">새로고침</el-button>
    </div>

    <el-table :data="packageList" stripe>
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="name" label="이름" min-width="160"/>
      <el-table-column label="이미지" width="100" align="center">
        <template #default="{ row }">
          <img
            v-if="row.imageUrl"
            :src="getImageUrl(row.imageUrl)"
            style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;"
            alt="상품 이미지"
          />
          <span v-else class="no-image">이미지 없음</span>
        </template>
      </el-table-column>
      <el-table-column prop="pointsAmount" label="포인트 수량" width="120">
        <template #default="{ row }">
          {{ formatPoints(row.pointsAmount) }}
        </template>
      </el-table-column>
      <el-table-column prop="priceDecimal" label="가격" width="100">
        <template #default="{ row }">
          ¥{{ formatPrice(row.priceDecimal) }}
        </template>
      </el-table-column>
      <el-table-column prop="badge" label="배지" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.badge" size="small">{{ row.badge }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="순서" width="80" align="center"/>
      <el-table-column prop="isActive" label="활성화" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success':'info'">{{ row.isActive ? '예' : '아니오' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isRecommended" label="추천" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isRecommended ? 'warning':'info'">{{ row.isRecommended ? '예' : '아니오' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="작업" width="280" align="center">
        <template #default="{ row }">
          <el-button size="small" :icon="Edit" @click="openEditDialog(row)">편집</el-button>
          <el-button size="small" type="primary" @click="togglePackage(row)">
            {{ row.isActive ? '비활성화' : '활성화' }}
          </el-button>
          <el-button size="small" type="warning" @click="toggleRecommended(row)">
            {{ row.isRecommended ? '추천 취소' : '추천' }}
          </el-button>
          <el-button size="small" type="danger" :icon="Delete" @click="deletePackage(row)">삭제</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="packageDialog"
      :title="editingId ? '포인트 상품 패키지 편집' : '포인트 상품 패키지 추가'"
      width="600px"
    >
      <el-form :model="packageForm" label-width="120px">
        <el-form-item label="상품 패키지명" required>
          <el-input v-model="packageForm.name" placeholder="예: 100,000 ALL + 동메달" />
        </el-form-item>
        <el-form-item label="상품 패키지 설명">
          <el-input
            v-model="packageForm.description"
            type="textarea"
            :rows="3"
            placeholder="상품 패키지의 상세 설명"
          />
        </el-form-item>
        <el-form-item label="포인트 수량" required>
          <el-input v-model.number="packageForm.pointsAmount" type="number" min="1" />
        </el-form-item>
        <el-form-item label="가격" required>
          <el-input v-model.number="packageForm.priceDecimal" type="number" min="0" step="0.01" />
        </el-form-item>
        <el-form-item label="상품 이미지">
          <div style="display:flex; gap:12px; align-items:center; width:100%">
            <el-upload
              :action="`${API_BASE_URL}/api/admin/uploads/cover`"
              name="cover-upload"
              :with-credentials="true"
              :show-file-list="false"
              :on-success="handleImageSuccess"
            >
              <img
                v-if="packageForm.imageUrl"
                :src="getImageUrl(packageForm.imageUrl)"
                style="width:120px;height:120px;object-fit:cover;border-radius:6px;"
                alt="상품 이미지"
              />
              <el-button v-else type="primary">이미지 업로드</el-button>
            </el-upload>
            <el-input
              v-model="packageForm.imageUrl"
              placeholder="이미지 URL을 직접 입력할 수도 있습니다 (선택사항)"
              style="flex: 1"
            />
          </div>
        </el-form-item>
        <el-form-item label="배지 표시">
          <el-select v-model="packageForm.badge" placeholder="배지 선택" clearable style="width: 100%">
            <el-option label="동메달" value="동메달" />
            <el-option label="은메달" value="은메달" />
            <el-option label="금메달" value="금메달" />
            <el-option label="다이아몬드" value="다이아몬드" />
            <el-option label="플래티넘" value="플래티넘" />
          </el-select>
        </el-form-item>
        <el-form-item label="정렬 순서">
          <el-input v-model.number="packageForm.sortOrder" type="number" min="0" />
        </el-form-item>
        <el-form-item label="활성화 여부">
          <el-switch v-model="packageForm.isActive" />
        </el-form-item>
        <el-form-item label="추천 여부">
          <el-switch v-model="packageForm.isRecommended" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="packageDialog=false">취소</el-button>
        <el-button type="primary" @click="savePackage">저장</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.package-mgmt {
  padding: 16px;
}
.title {
  margin: 0 0 12px;
}
.toolbar {
  display: flex;
  gap: 8px;
  margin: 10px 0;
}
.no-image {
  color: #999;
  font-size: 12px;
}
</style>
